class MyTable {
    constructor(dataArr = [], domRoot, conf) {
        this.dataArr = dataArr
        this.domRoot = domRoot


        this.defaultConf = {
            pageSize: 20,
            page: 1
        }
        // 在默认配置的基础上追加用户的配置
        // this.conf = Object.assign(this.defaultConf,conf)
        this.conf = {
            ...this.defaultConf,
            ...conf
        }

        console.log("MyTable conf=", this.conf);

        this.domFrame = `
        <table border="1" cellspacing="0" id="mytable">
        <thead>
            <tr>${this.generateThs(this.dataArr[0], this.conf["dataAttrDict"])}</tr>
        </thead>
        <tbody></tbody>
    </table>
        `
        
        this.render()
    }

    // 生成表头
    generateThs(itemObj, dict) {
        console.log("generateThs dict=", dict);
        let ths = ""
        ths += `<td>序号</td>`
        for (let attr in itemObj) {
            ths += `<td>${dict ? dict[attr] : attr}</td>`
        }
        return ths
    }

    // 生成item的td结构
    generateItemTds(itemObj, index) {
        let tds = ""
        tds += `<td>${index}</td>`
        for (let attr in itemObj) {
            tds += `<td>${itemObj[attr]}</td>`
        }
        return tds
    }

    render() {
        // 渲染表头（页面已经有东西了）
        this.domRoot.innerHTML = this.domFrame
        // 从半成品页面中找出tbody
        this.tbody = document.querySelector("tbody")
        this.turnToPage(this.conf.page)
    }

    // 翻页方法
    turnToPage(page) {
        let html = ""
        let arr = this.dataArr.slice(this.conf.pageSize * (page - 1), this.conf.pageSize * page)
        arr.forEach(
            (item, index) => {
                html += `<tr>${this.generateItemTds(item, index + 1)}</tr>`
            }
        )
        this.tbody.innerHTML = html
    }
}